package com.Policing.Maintain;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.Policing.Scan.qrcode.util.Constant;
import com.Policing.Scan.zxing.activity.CaptureActivity;
import com.Policing.Since_case.Since_case;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnDismissListener;
import com.bigkoo.alertview.OnItemClickListener;
import com.Policing.Adapter.Maintain_adapter;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.R;
import com.Policing.misc.Accompaniment;
import com.Policing.uhf.util.DataTransfer;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.senter.iot.support.openapi.uhf.UhfD2;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2019/4/25.
 */

public class Maintain_add extends Activity implements OnDismissListener {
    private final Accompaniment accompaniment = Accompaniment.newInstanceOfResource(this, R.raw.tag_inventoried);
    //播放声音
    private Handler accompainimentsHandler;
    private boolean state;
    private Button add;
    private ImageView fh;
    private boolean isrfid=true;
    private String deviceId;//设备id
    private String id,name,partId;
    private String err="";
    private String url="http://"+ Ip_Set.IP+"/api/devicePartMainAdd";
    ArrayList<Map<String,Object>> data;
    private ListView maintain_lv;
    private Button put_bt;//提交
    private String add_url="http://"+ Ip_Set.IP+"/api/devicePartAdd";
    private Handler handler = new Handler();
    private TextView category;//设备名称
    private EditText editText;
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    private String rfid,number;
    private List<String> partid = new ArrayList<>();
    private List<Boolean> booleen = new ArrayList<>();
    private boolean stop_rfid =true;
    private Button scan_img;
    private List<String> rfid_data = new ArrayList<>();
    private final Runnable accompainimentRunnable = new Runnable() {
        @Override
        public void run() {
            accompaniment.start();
            accompainimentsHandler.removeCallbacks(this);
        }
    };
    private Button RFID;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.maintain_add);
        HandlerThread htHandlerThread = new HandlerThread("");
        htHandlerThread.start();
        accompainimentsHandler = new Handler(htHandlerThread.getLooper());
        SharedPreferences mm = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        id = mm.getString("id","");
        indata();
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                editText.selectAll();
                category.setText("");
                if (editText.getText().toString().equals(number)){
                    category.setText(name);
                    Maintain_adapter maintain_adapter = new Maintain_adapter(Maintain_add.this,list);
                    maintain_lv.setAdapter(maintain_adapter);
                }else Toast.makeText(Maintain_add.this,"请扫描正确的设备",Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void indata() {
        scan_img = (Button) findViewById(R.id.scan_img);
        scan_img.setOnClickListener(v -> startQrCode());
        fh = (ImageView) findViewById(R.id.fh);
        fh.setOnClickListener(v -> finish());
        put_bt = (Button) findViewById(R.id.put_bt);
        put_bt.setOnClickListener(v -> {
            if (category.getText().toString().equals("")) {
                Toast.makeText(Maintain_add.this, "请先读取设备再试", Toast.LENGTH_SHORT).show();
                return;
            }
            String status = "1";
            for (int i = 0; i < booleen.size(); i++) {
                if (!booleen.get(i)) {
                    status = "0";
                }
            }
            if (status.equals("0")) {
                post("", "0", "0", "1");
                // finish();
            } else {
                post("", "0", "0", "0");

            }
        });
        add  = (Button) findViewById(R.id.add);
        name = getIntent().getStringExtra("name");
        deviceId = getIntent().getStringExtra("partId");
        maintain_lv = (ListView) findViewById(R.id.maintain_lv);
        category = (TextView) findViewById(R.id.category);
        number = getIntent().getStringExtra("number");
        editText = (EditText) findViewById(R.id.asset_tag);
        rfid = getIntent().getStringExtra("rfid");
        RFID = (Button) findViewById(R.id.check_rfid);
        editText.setInputType(InputType.TYPE_NULL);
        RFID.setOnClickListener(v -> {
            try {
                if (isrfid==true){
                    if (UhfD2.getInstance().init() == true){
                        UhfD2.getInstance().iso18k6cSetAccessEpcMatch(UhfD2.UmdEpcMatchSetting.newInstanceOfDisable());
                    }
                    isrfid = false;
                }

            }catch (Exception E){
                Toast.makeText(Maintain_add.this,"没有RFID模块",Toast.LENGTH_SHORT).show();
                return;
            }
            if (stop_rfid){
                stop_rfid=false;
                start_read();
                RFID.setText("停止读取");
            }else {
                stop_rfid=true;
                state =false;
                RFID.setText("开启RFID");
            }

        });
        add.setOnClickListener((View.OnClickListener) v -> {
            if (category.getText().toString().equals("")){
                Toast.makeText(Maintain_add.this,"请先读取设备再试",Toast.LENGTH_SHORT).show();
                return;
            }
            final View  view=(LinearLayout) getLayoutInflater().inflate(R.layout.maintain_item,null);
            final AlertDialog.Builder builder = new AlertDialog.Builder(Maintain_add.this);
            builder.setTitle("添加关键部位").setIcon(android.R.drawable.ic_dialog_info).setView(view)
                    .setNegativeButton("取消", null);
            builder.setPositiveButton("确定", (dialog, which) -> {
                EditText part = (EditText) view.findViewById(R.id.part);
                EditText brand = (EditText) view.findViewById(R.id.brand);
                EditText model = (EditText) view.findViewById(R.id.model);
                if (part.getText().toString().trim().equals("")||brand.getText().toString().trim().equals("")||model.getText().toString().trim().equals("")){
                    Toast.makeText(Maintain_add.this,"添加失败！！请完善数据后重试！！！",Toast.LENGTH_SHORT).show();
                    return;
                }
                Add_part(part.getText().toString().trim(),brand.getText().toString().trim(),model.getText().toString().trim());

            });
            builder.show();
        });
        String jsonData = getIntent().getStringExtra("data");
        data = new Gson().fromJson(jsonData, new TypeToken<ArrayList<Map<String,Object>>>(){}.getType());
        Log.i("datadata",data.toString());
        for (int i =0;i<data.size();i++){
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("coding_name", data.get(i).get("partName"));
            map.put("maintain_img","");
            booleen.add(true);
            partid.add((String) data.get(i).get("partId"));
            Log.i("datadata", (String) data.get(i).get("partId"));
            list.add(map);
        }

        maintain_lv.setOnItemClickListener((parent, view, position, id) -> {
           if (booleen.get(position)){
               new AlertView("保养", "是否异常", "否",new String[]{"是"}, null, Maintain_add.this, AlertView.Style.Alert, new OnItemClickListener() {
                   @Override
                   public void onItemClick(Object o, int i) {
                       //正常：position=-1,异常 position=0
                       if (i==0){
                           Map<String, Object> map = new HashMap<String, Object>();
                           map.put("coding_name", list.get(position).get("coding_name"));
                           map.put("maintain_img",R.mipmap.yichang);
                           list.set(position,map);
                           err = String.valueOf(position);
                           Maintain_adapter maintain_adapter = new Maintain_adapter(Maintain_add.this,list);
                           maintain_lv.setAdapter(maintain_adapter);
                           booleen.set(position,false);
                           partId = partid.get(position);
                           Intent intent = new Intent(Maintain_add.this,Maintain_Scheme.class);
                           intent.putExtra("partid",partId);
                           intent.putExtra("number",number);
                           intent.putExtra("state",position);
                           intent.putExtra("err",err);
                           Log.i("0000000",partid+number);
                           startActivityForResult(intent,1);

                       }
                       if (i==-1){

                       }

                   }
               }).setCancelable(true).setOnDismissListener( Maintain_add.this).show();
           }

        });
    }

    private void Add_part(final String part, final String brand, final String model){
        new Thread(() -> {
            OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
            FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
            formBody.add("deviceId",deviceId)
                    .add("brand",brand)
                    .add("model",model)
                    .add("source", Since_case.set().getSource())
                    .add("part",part);

            final Request request = new Request.Builder()//创建Request 对象。
                    .url(add_url)
                    .post(formBody.build())//传递请求体
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    //回调方法的使用与get异步请求相同
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(Maintain_add.this,"请连接网络后重试",Toast.LENGTH_SHORT).show();
                            Log.i("123123", "error");
                        }
                    });

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String responseData = response.body().string();
                    handler.post(() -> {
                        try {
                            JSONObject jsonObject = new JSONObject(responseData);
                            if (jsonObject.getString("state").equals("1"))
                            {
                                Map<String, Object> map = new HashMap<String, Object>();
                                map.put("coding_name", jsonObject.getString("partName"));
                                map.put("maintain_img","");
                                booleen.add(true);
                                partid.add(jsonObject.getString("partId"));
                                list.add(map);
                                Maintain_adapter maintain_adapter = new Maintain_adapter(Maintain_add.this,list);
                                maintain_lv.setAdapter(maintain_adapter);
                                Toast.makeText(Maintain_add.this,"添加成功",Toast.LENGTH_SHORT).show();
                            }
                            else if (jsonObject.getString("state").equals("0")){
                                Toast.makeText(Maintain_add.this,"添加失败",Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    });

                }
            });

        }).start();

    }

    private void start_read(){
        state=true;
        UhfD2.getInstance().iso18k6cRealTimeInventory(1, new UhfD2.UmdOnIso18k6cRealTimeInventory() {
            @Override
            public void onTagInventory(UhfD2.UII uii, UhfD2.UmdFrequencyPoint umdFrequencyPoint, Integer integer, UhfD2.UmdRssi umdRssi) {
                if (!rfid_data.contains(DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4))){
                    rfid_data.add(DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4));
                    if (rfid.equals(DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4))){
                        runOnUiThread(() -> {
                            category.setText(name);
                            Maintain_adapter maintain_adapter = new Maintain_adapter(Maintain_add.this,list);
                            maintain_lv.setAdapter(maintain_adapter);
                        });
                    }
                    trigTagAccompainiment();//播放声音
                }


            }

            @Override
            public void onFinishedSuccessfully(Integer integer, int i, int i1) {
                onFinishedOnce();
            }
            private void onFinishedOnce() {
                if (state) {
                    start_read();
                }
            }
            @Override
            public void onFinishedWithError(UhfD2.UmdErrorCode umdErrorCode) {
                onFinishedOnce();
            }
        });


    }
    @Override
    protected void onDestroy() {
        if (accompainimentsHandler != null) {
            accompainimentsHandler.getLooper().quit();
        }
        accompaniment.release();
        stop_rfid=false;
        try {
            UhfD2.getInstance().uninit();
        }catch (Exception e){
        }

        super.onDestroy();
    }
    private void trigTagAccompainiment() {
        accompainimentsHandler.post(accompainimentRunnable);
    }

    @Override
    public void onDismiss(Object o) {

    }
    public void post(final String remark, final String iserror, final String parid,final String status) {
        new Thread(() -> {
            OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
            FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
            formBody.add("userId",id)
            .add("deviceNumber",number)
            .add("partId",parid)
            .add("status",status)
            .add("iserror",iserror)
            .add("source",Since_case.set().getSource())
            .add("remark",remark); //传递键值对参数

            final Request request = new Request.Builder()//创建Request 对象。
                    .url(url)
                    .post(formBody.build())//传递请求体
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    //回调方法的使用与get异步请求相同
                    handler.post(() -> {
                        Toast.makeText(Maintain_add.this,"请连接网络后重试",Toast.LENGTH_SHORT).show();
                        Log.i("123123", "error");
                    });

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String responseData = response.body().string();
                    Log.i("statestate",responseData);
                    handler.post(() -> {
                        try {
                            JSONObject jsonObject = new JSONObject(responseData);
                            if (jsonObject.getString("state").equals("1"))
                            {
                                Toast.makeText(Maintain_add.this,"提交成功",Toast.LENGTH_SHORT).show();
                                if (iserror.equals("0")||iserror.equals("2")){
                                    finish();
                                }
                            }
                            else   if (jsonObject.getString("state").equals("0"))
                            {
                                Toast.makeText(Maintain_add.this,"提交失败",Toast.LENGTH_SHORT).show();

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    });

                }
            });

        }).start();

    }

    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(Maintain_add.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Maintain_add.this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(Maintain_add.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Maintain_add.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(Maintain_add.this, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Maintain_add.this, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Maintain_add.this, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1&&resultCode==1){
            int position = Integer.parseInt(data.getExtras().getString("err"));
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("coding_name", list.get(position).get("coding_name"));
            map.put("maintain_img","");
            booleen.set(position,true);
            list.set(position,map);
            Maintain_adapter maintain_adapter = new Maintain_adapter(Maintain_add.this,list);
            maintain_lv.setAdapter(maintain_adapter);
        }
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            if (scanResult.equals(number)){
                category.setText(name);
                Maintain_adapter maintain_adapter = new Maintain_adapter(Maintain_add.this,list);
                maintain_lv.setAdapter(maintain_adapter);
            }else Toast.makeText(Maintain_add.this,"请扫描正确的设备",Toast.LENGTH_SHORT).show();
        }
    }
}
